import {
	observable,
	action
} from 'mobx';
import {
	Button,
	message,
	Modal
} from 'antd';
import {
	WeaForm,
	WeaLogView
} from 'comsMobx';
import {
	WeaLocaleProvider
} from 'ecCom';
import classnames from 'classnames';
import * as mobx from 'mobx';
import {
	authorized,
	detachable,
	checkAuthAndDetach,
	getPinYin
} from '../apis/common';
import {
	i18n
} from '../public/i18n';
import {
	logTypeDef
} from '../public/logType';
import {findIndex} from 'lodash';
import moment from 'moment';
const getLabel = WeaLocaleProvider.getLabel;

const confirm = Modal.confirm;
const info = Modal.confirm;
const {
	LogStore
} = WeaLogView;

export default class HrmBaseStore {
	constructor(){
	}
	/********************* unobservable list *********************/
	logTypeDef = logTypeDef;
	getPinYin = getPinYin;
	toJS = mobx.toJS;
	moment = moment;
	basicDialogParams = {
		moduleName: 'hrm',
		style: {
			width: 520,
			height: 300
		},
		visible: false,
		title: '',
	}
	menuIconCollection = {
		save: 'icon-coms-Preservation',
		create: 'icon-coms-New-Flow',
		modify: 'icon-coms-edit',
		remove: 'icon-coms-Batch-delete',
		copy: 'icon-coms-form-copy',
		entry: 'icon-coms-edit',
		setting: 'icon-coms-Flow-setting',
		log: 'icon-coms-Print-log',
		multiModify: 'icon-coms-BatchEditing',
		import: ' icon-coms-leading-in',
		export: 'icon-coms-export',
		search: 'icon-coms-search',
		sync: 'icon-coms-Update-synchronization',
		done: 'icon-coms-Upload-successfully',
		selectAll: 'icon-coms-batch'
	}
	getBasicMenus = (logTypeKey, targetId = null) => {
		let arr = [];
		if(logTypeKey){
			arr.push({
				key: '99',
				content: i18n.label.log(),
				icon: <i className={this.menuIconCollection.log}/>,
				onClick: () => this.showLog({logSmallType: this.logTypeDef[logTypeKey], targetId})
			});
		}
		return arr;
	}

	dialogPropsDef = {
		moduleName: 'hrm',
		visible: false,
		title: '',
		moreBtn: {
			datas: []
		},
		// hasScroll: true
	}
	refsDialogPropsDef = {
		moduleName: 'hrm',
		visible: false,
		title: '',
	}
	dateSwitchTypeList = ['year', 'month', 'week', 'day'];
	formTarget = {}; //form collection
	opId = null; //数据操作对象主键ID
	authorizationInfo = {};

	/**
	 * 权限验证
	 * @param  {String}   moduleName [模块名]
	 * @param  {Object}   params     [restful request url params]
	 * @param  {Function} callback   [验证通过后的callback function]
	 * @return {null}
	 */
	checkAuthorized = (moduleName, params, callback, apiMethod, needCheckDetachable = false) => {
		if (needCheckDetachable) {
			checkAuthAndDetach(moduleName, params, apiMethod).then(rs => {
				rs.map((result, index) => {
					if (result.status === '1') {
						switch (index) {
							case 0:
								const init = !result.hasRight;
								this.authorizationInfo = result;
								this.containerInitFinished = {
									...this.containerInitFinished,
									init,
									authorized: result.hasRight,
									userId: result.userId
								}
								this.containerInitFinished.authorized && callback && callback();
								break;
							case 1:
								this.containerInitFinished.detachable = result.detachable === '0' ? false : true
								break;
						}
					}
				})
			})
		} else {
			authorized(moduleName, params, apiMethod).then((data) => {
				if (data.status === '1') {
					const init = !data.hasRight;
					this.authorizationInfo = data;
					this.containerInitFinished = {
						init,
						authorized: data.hasRight
					}
					this.containerInitFinished.authorized && callback && callback();
				}
			}, error => {
				this.containerInitFinished = {
					init: true,
					authorized: false
				}
			});
		}
	}

	/**
	 * 获取激活的tab页下标
	 * @param  {Array} tabs [tabData数组]
	 * @param  {String} key [tabKey]
	 * @return {Integer} [tab下标]
	 */
	getTabIndex(tabs, key) {
		if (tabs != null && tabs.length > 0) {
			return findIndex(tabs, {
				viewCondition: key
			})
		}
		return -1;
	}

	convertToMenus = (buttons) => {
		let menus = [];
		buttons.map((btn, index) => {
			const {
				props
			} = btn;
			menus.push({
				key: index.toString(),
				content: props.children,
				icon: <i className={this.menuIconCollection[props.op]}/>,
				onClick: props.onClick,
				disabled: props.disabled || false
			});
		})
		return menus;
	}

	/**
	 * 获取WeaTop按钮、WeaTab按钮以及右键菜单列表
	 * @param  {Object} tabConfig [description]
	 * @return {Object}           [description]
	 */
	btnsAndMenus = (tabConfig) => {
		let topBtnDef = [], //WeaTop按钮
			menuDef = [], //右键菜单
			tabBtnDef = []; //WeaTab按钮

		const activeTabIndex = this.getTabIndex(tabConfig.tabs, tabConfig.activeTabKey);
		if (tabConfig.activeTabKey === '' || activeTabIndex < 0) {
			return {
				btns: topBtnDef,
				menus: menuDef,
				tabBtnDef: tabBtnDef
			}
		}
		const tab = tabConfig.tabs[activeTabIndex];
		const {
			topButtonDef,
			tabButtonDef
		} = tab;
		topButtonDef && topButtonDef.map((def, idx) => { //组织WeaTop按钮
			const lbl = (typeof(def.label) == 'function' ? def.label() : def.label);
			switch (def.comType) {
				case 'button':
					let disabled = false;
					if (def.checkAction)
						disabled = this[def.checkAction];
					topBtnDef.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@l5ux5e@${idx}`} type={def.type} onClick={def.onClickHandle} disabled={disabled || def.disabled}>{lbl}</Button>);
					menuDef.push({ //组织右键菜单
						key: `$top-btn-${idx}`,
						content: lbl,
						icon: <i className={def.rightMenuIcon || def.icon}/>,
						onClick: def.onClickHandle,
						disabled: disabled || def.disabled || false
					})
					break;
				default:
					break;
			}
		});
		tabButtonDef && tabButtonDef.map((def, idx) => { //组织WeaTab按钮
			const lab = (typeof(def.label) == 'function' ? def.label() : def.label);
			switch (def.comType) {
				case 'button':
					let disabled = false;
					if (def.checkAction)
						disabled = this[def.checkAction];
					const classes = classnames({
						[def.icon]: true,
						'tabBtn': true,
						'tabBtn-active': !disabled,
						'tabBtn-disable': disabled
					});
					tabBtnDef.push(
						<i
							className={classes}
							title={lab}
							onClick={!disabled ? def.onClickHandle : null} 
						/>
					);
					break;
				default:
					break;
			}
		});
		return {
			btns: topBtnDef,
			menus: menuDef,
			tabBtnDef: tabBtnDef
		}
	}

	confirmInfo = (props) => {
		confirm({ ...props,
			title: props.title || i18n.confirm.defaultTitle(),
			okText: i18n.label.ok(),
			cancelText: i18n.label.cancel()
		});
	}

	hint = (props) => {
		info({ ...props,
			title: i18n.confirm.defaultTitle(),
			okText: i18n.label.ok(),
		});
	}

	/**
	 * 初始化formStore
	 * @param  {String} formName [form's name]
	 * @param  {Array} fields   [form field definition]
	 * @return {null}
	 */
	setFormData = (formName, fields) => {
		this.formTarget[`${formName}Fields`] = fields;
		this.formTarget[formName] = new WeaForm();
		this.formTarget[formName].initFormFields(fields);
	}

	/**
	 * 获取表格数据的通用方法
	 * @param  {String} tableStore [tableStore's name]
	 * @param  {Function} api        [restful api function]
	 * @param  {Object} params     [restful request url params]
	 * @return {null}
	 */
	requestTableData = (tableStore, api, params = {}, callback) => {
		api(params).then(data => {
			if (data.status === '1') {
				tableStore.getDatas(data.sessionkey, 1);
				callback && callback();
			} else
				message.error(data.message);
		}, error => {
			message.error(i18n.message.actionError());
		});
	}

	showLog = (logTypeParams) => {
		window.setLogViewProps({
			...logTypeParams
		});
	}
	/********************* unobservable list *********************/

	/********************* observable list *********************/
	@observable containerInitFinished = { //模块初始化状态
		init: false,
		authorized: false,
		detachable: false
	}
	@observable showError = new Date().getTime(); //状态刷新，组件引用该值监听变化重新render
	@observable dialogParams = {}; //模态框参数

	// monitorI18n = () => {
	// 	this.i18nLoaded;
	// }

	// monitor = autorun(this.monitorI18n)
	/********************* observable list *********************/

	/********************* action list *********************/
	@action definedColumn = (table) => {//显示列定义
		table.setColSetVisible(true);
		table.tableColSet(true);
	}
	/********************* action list *********************/

	getLocale() {
		return {
			firstDayOfWeek: 0,
			lang: {
				format: {
					eras: [getLabel(383357, "公元前"), getLabel(383358, "公元")],
					months: [getLabel(1492, "一月"), getLabel(1493, "二月"), getLabel(383385, "三月"), getLabel(383387, "四月"), getLabel(1496, "五月"), getLabel(383392, "六月"),
						getLabel(383393, "七月"), getLabel(383394, "八月"), getLabel(383395, "九月"), getLabel(383396, "十月"), getLabel(383397, "十一月"), getLabel(383398, "十二月")
					],
					shortMonths: [getLabel(1492, "一月"), getLabel(1493, "二月"), getLabel(383385, "三月"), getLabel(383387, "四月"), getLabel(1496, "五月"), getLabel(383392, "六月"),
						getLabel(383393, "七月"), getLabel(383394, "八月"), getLabel(383395, "九月"), getLabel(383396, "十月"), getLabel(383397, "十一月"), getLabel(383398, "十二月")
					],
					weekdays: [getLabel(398, "星期天"), getLabel(392, "星期一"), getLabel(393, "星期二"), getLabel(394, "星期三"), getLabel(395, "星期四"),
						getLabel(396, "星期五"), getLabel(397, "星期六")
					],
					shortWeekdays: [getLabel(16106, "周日"), getLabel(16100, "周一"), getLabel(16101, "周二"), getLabel(16102, "周三"), getLabel(16103, "周四"), getLabel(16104, "周五"),
						getLabel(16105, "周六")
					],
					veryShortWeekdays: [getLabel(82920, "日"), getLabel(82914, "一"), getLabel(82915, "二"), getLabel(82916, "三"), getLabel(82917, "四"), getLabel(82918, "五"), getLabel(82919, "六")],
					ampms: [getLabel(383408, "上午"), getLabel(383409, "下午")],
					datePatterns: [`yyyy'${getLabel(383372,"年")}'M'${getLabel(383373,"月")}'d'${getLabel(383374,"日")}' EEEE`, `yyyy'${getLabel(383372,"年")}'M'${getLabel(383373,"月")}'d'${getLabel(383374,"日")}'`, "yyyy-M-d", "yy-M-d"],
					timePatterns: [`ahh'${getLabel(383411,"时")}'mm'${getLabel(383412,"分")}'ss'${getLabel(383414,"秒")}' 'GMT'Z`, `ahh'${getLabel(383411,"时")}'mm'${getLabel(383412,"分")}'ss'${getLabel(383414,"秒")}'`, "H:mm:ss", "ah:mm"],
					dateTimePattern: '{date} {time}'
				}
			},
		}
	}
	/********************* tableEdit props & functions *********************/
}